/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package commonBackingBean;

import entities.City;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import sessionBeans.CityFacadeLocal;
import tools.StaticFields;

/**
 *
 * @author myPC
 */
@Named
@SessionScoped
public class CityBean implements java.io.Serializable {

    @EJB
    private CityFacadeLocal cityFacadeLocal;
    private LinkedHashMap<String, Integer> cityMap;
    private City city;

    public LinkedHashMap<String, Integer> getCityMap() {
        if (null == cityMap || cityMap.isEmpty()) {
            cityMap = new LinkedHashMap<>();
            List<City> listCity = cityFacadeLocal.findAll();
            for (Iterator<City> it = listCity.iterator(); it.hasNext();) {
                City city2 = it.next();
                cityMap.put(city2.getName(), city2.getId());
            }
        }
        return cityMap;
    }

    public String add() {
        List<City> cityList = cityFacadeLocal.getQueryResultList("select * from city where locate('" + this.city.getName() + "',name)");
        if (null == cityList || cityList.isEmpty()) {
            cityFacadeLocal.create(city);
        } else {
            FacesContext.getCurrentInstance().addMessage("ok", new FacesMessage(StaticFields.MESSAGES_PROPTES.getString("failedAdd1")));
        }
        return null;
    }

    /**
     * @return the city
     */
    public City getCity() {
        return city;
    }

    /**
     * @param city the city to set
     */
    public void setCity(City city) {
        this.city = city;
    }

    public void save() {
        cityFacadeLocal.edit(city);
    }

    public void deleteRow(FacesContext context, UIComponent toValidate, Object value) {
        cityFacadeLocal.remove((City) value);
    }

}
